package com.yiwei.ydd.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.LoginBean;
import com.yiwei.ydd.api.bean.ModifySendBean;
import com.yiwei.ydd.api.bean.PagesDetailBean;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.Const;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.event.OldUserLoginEvent;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.UI;
import com.yiwei.ydd.util.Util;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class LoginActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_wechat)
    TextView btnWechat;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.btn_close)
    ImageView btnClose;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_change_phone)
    TextView btnChangePhone;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.btn_agreement)
    TextView btnAgreement;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    private Unbinder unbiner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initWebViewBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
//        editPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus) {
//                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                }
//            }
//        });
//        editCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (hasFocus) {
//                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                }
//            }
//        });
    }

    public void getPagesDetail() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        ((BaseActivity) this).loadingDialog.show();
        PagesDetailBean item = new PagesDetailBean();
        item.keyword = Const.PageDetailType.APP_SERVICE;
        Api.api_service.getPagesDetail(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        ((BaseActivity) this).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Intent intent1 = new Intent(this, WebViewActivity.class);
                    intent1.putExtra("content", result.datas.content);
                    intent1.putExtra("title", result.datas.title);
                    this.startActivity(intent1);
                });
    }


    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setEnabled(false);
            btnSendCode.setText((millisUntilFinished / 1000) + "s");
            btnSendCode.setTextColor(0xFFCCCCCC);
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);

        btnSendCode.setText("获取验证码");
        btnSendCode.setTextColor(0xFFFB5E01);
    }

    public void getSms(String phone) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        ModifySendBean item = new ModifySendBean();
        item.phone = phone;
        ((BaseActivity) this).loadingDialog.show();
        Api.api_service.getSmsSend(item).compose(RxLifeUtil.checkOn(((BaseActivity) this))).
                doFinally(() -> {
                    try {
                        ((BaseActivity) this).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    timer.start();
                    ToastUtil.makeText(this, "发送成功，请注意查收");
                });
    }

    public void getLogin(String phone, String code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        LoginBean item = new LoginBean();
        item.phone = phone;
        item.verify_code = code;
        ((BaseActivity) this).loadingDialog.show();
        Api.api_service.getLogin(item).compose(RxLifeUtil.checkOn(((BaseActivity) this))).
                doFinally(() -> {
                    try {
                        ((BaseActivity) this).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    UserInfoGlobal.saveLoginInfo(result.datas);
                    if (result.datas.is_newuser.equals("1")) {
//                        new InviteFriendDialog(this).show();
                        Util.startActivity(this, InviteFriendRegisterActivity.class);
                        finish();
                        return;
                    }
                    EventBus.getDefault().post(new OldUserLoginEvent());
                    ToastUtil.makeText(this, "登录成功");
                    finish();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_wechat, R.id.btn_close, R.id.btn_send_code, R.id.btn_change_phone, R.id.btn_submit, R.id.btn_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_wechat:
                Util.startActivity(this, ChatCenterActivity.class);
                break;
            case R.id.btn_close:
                editPhone.setText("");
                break;
            case R.id.btn_send_code:
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(this, "手机号不能为空");
                    return;
                }
                getSms(UI.toString(editPhone));
                break;
            case R.id.btn_change_phone:
                Util.startActivity(this, ChangePhoneActivity.class);
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(this, "手机号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(this, "验证码不能为空");
                    return;
                }
                getLogin(UI.toString(editPhone), UI.toString(editCode));
                break;
            case R.id.btn_agreement:
                getPagesDetail();
                break;
        }
    }
}
